package com.qunar.wan.web.controller;

import com.google.common.base.Preconditions;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.qunar.wan.util.ImageHelper;
import com.qunar.wan.web.controller.common.AbstractController;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * User: huiming.suo
 * Date: 11/28/13 Time: 4:01 PM
 */

@Controller
@RequestMapping(value = "fileupload")
public class FileController extends AbstractController {

    @Value("#{settings['imgpath']}")
    private String upload_img_path = "";
    private final static String HEAD_PATH = "head";
    private final static String POSTER_PATH = "poster";

    @RequestMapping("uploadImg")
    @ResponseBody
    public Object postRequest(HttpServletRequest request, @RequestParam("picture") MultipartFile[] imageFiles,
                              @RequestParam("picx") int picx, @RequestParam("picy") int picy, @RequestParam("picw") int picw,
                              @RequestParam("pich") int pich, @RequestParam("flagPic") int flagPic, @RequestParam("picType") String picType) throws Exception {

        if (imageFiles.length <= 0 || !(HEAD_PATH.equals(picType) || POSTER_PATH.equals(picType))) {
            logger.error("图片上传参数出问题，imageFiles长度{},图片类型{}", imageFiles.length, picType);
            return errorJson(102, "没有图片信息");
        }
        long start = System.currentTimeMillis();
        MultipartFile multipartFile = imageFiles[0];
        Preconditions.checkNotNull(multipartFile);

        //获取图片
        String fileName = multipartFile.getOriginalFilename();
        InputStream inputStream = multipartFile.getInputStream();

        String uploadPath = upload_img_path + picType + "imgs/";

        // 图片后缀名
        List<String> splitList = Lists.newArrayList(Splitter.on('.').split(fileName));
        String fileSuffix = splitList.get(splitList.size() - 1);

        // 文件名：当前时间+随机数
        int randomNum = (int) (Math.random() * 10000);
        long currentTime = System.currentTimeMillis();

        String imgName = new StringBuilder(String.valueOf(currentTime)).append(randomNum).append(".").append(fileSuffix).toString();
        try {
            ImageHelper.cutImage(inputStream, uploadPath + imgName, fileSuffix, picx * flagPic, picy * flagPic,
                    picw * flagPic, pich * flagPic);
            logger.info("图片上传成功,存放路径{}", uploadPath + imgName);
        } catch (IOException e) {
            logger.error("切割图片出问题,图片流{}，图片存放路径{},后缀名{}", new Object[]{inputStream, uploadPath, fileSuffix});
            return errorJson(101, "上传失败", System.currentTimeMillis() - start);
        }

        return dataJson(imgName, System.currentTimeMillis() - start);
    }
}
